package filter;

import model.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author: 杨青桦
 * @Description: 身份验证过滤器
 * @Date: 2018/3/7 10:14
 */
@Component
public class UserAuthFilter implements Filter {

    private static final Log logger = LogFactory.getLog(UserAuthFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    /**
     * @Author: 杨青桦
     * @Description:  1.校验用户名 2.校验医院 3.校验数据id
     * @Date: 2018/3/8 16:23
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            String root = ((HttpServletRequest) request).getContextPath();
            HttpSession session = httpServletRequest.getSession();
            String path = httpServletRequest.getServletPath();
            //医院端调用 放行
            if (path.indexOf("login") > 0) {
                chain.doFilter(request, response);
            } else {
                User user = (User) session.getAttribute("loginUser");
                if (user != null) {
                    System.out.println(user.getName() + " " + path);
                    chain.doFilter(request, response);
                } else {
                    System.out.println("未登录");
                    httpServletResponse.sendRedirect(root + "/index.html");
                }
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void destroy() {

    }


}
